package com.longxiao.service.message;

import com.longxiao.enums.SmsTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;

/**
 * 短信发送通道
 * Created by Administrator on 2017/5/25.
 */
@Service("smsSender")
public class SmsSender {

    Logger logger = LoggerFactory.getLogger(SmsSender.class);

    String corpId = "TCLKJ03715";
    String pwd = "tcyw0814@";



    /**
     * 发送短信
     * @param mobile
     * @param content
     * @param sendTime 传""
     * @return
     */
    public int send(String mobile, String content, String sendTime) {
        URL url = null;
        String send_content= null;//发送内容
        int inputLine = 0;
        BufferedReader in = null;
        try {
            send_content = URLEncoder.encode(content.replaceAll("<br/>", " "), "GBK");
            // https://inolink.com/+函数
            String strUrl = "https://inolink.com/ws/BatchSend2.aspx?CorpID=" + corpId + "&Pwd=" + pwd + "&Mobile=" + mobile + "&Content=" + send_content+"&Cell=&SendTime=" + sendTime;
            logger.info("send|发送短信|mobile:{}|content:{}", mobile, content);
            url = new URL(strUrl);
            // url = new URL("http://inolink.com/BatchSend2.aspx?CorpID="+corpId+"&Pwd="+pwd+"&Mobile="+mobile+"&Content="+send_content+"&Cell=&SendTime="+sendTime);
            in = new BufferedReader(new InputStreamReader(url.openStream()));
            // 返回大于0都是成功的
            inputLine = new Integer(in.readLine()).intValue();
            logger.info("send|发送短信|返回码：{}(返回大于0都是成功的)", inputLine);
        } catch (Exception e) {
            inputLine = -2;
            logger.error("send|发送短信|系统异常|", e);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return inputLine;
    }

    /**
     * 发送随机短信验证码
     * @param mobile
     * @param template
     * @return
     */
    public int sendRandomCode(String mobile, SmsTemplate template, String validCode) {
        String content = template.getTemplate().replace("{valideCode}", validCode);
        return send(mobile, content, "");
    }
}
